package com.boxin.ims.modules.wechat.busi;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.boxin.framework.base.dao.DaoHelper;
import com.boxin.framework.base.utils.Constants;
import com.boxin.framework.base.utils.DateUtils;
import com.boxin.ims.modules.wechat.entity.ImageMessage;
import com.boxin.ims.modules.wechat.entity.Lottery;
import com.boxin.ims.modules.wechat.entity.LotteryRecord;
import com.boxin.ims.modules.wechat.entity.TextMessage;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.entity.share.CircleShare;
import com.boxin.ims.modules.wechat.entity.share.ShareConfig;
import com.boxin.ims.modules.wechat.entity.share.ShareRule;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.service.share.CircleShareService;
import com.boxin.ims.modules.wechat.service.share.ShareConfigService;
import com.boxin.ims.modules.wechat.service.share.ShareRuleService;
import com.boxin.ims.modules.wechat.utils.ScoreUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;


/**
 * @author Jakemanse
 * @date 2013-10-2
 * @function <p> 朋友圈 分享处理 </p>
 */
@Service
public class ShareProcessor extends BusinessProcessor{
	

	@Autowired
	CircleShareService circleShareService;
	
	
	@Autowired
	ShareConfigService shareConfigService;
	
	@Autowired
	ShareRuleService shareRuleService;
	
	@Autowired
	WechatMemberService wechatMemberService;
	
	@Autowired
	DaoHelper daoHelper;
	
	public ShareProcessor(){
		super();
	}
	
	
	
	
	public ShareProcessor(WeChat weChat,String openId,HttpServletRequest request, HttpServletResponse response) {
		super(weChat,openId);
		this.request = request;
		this.response = response;
	}
	
	
	
	@Override
	public ProcessMessage process() {
		String reply = "对不起该服务还未启动，感谢您的参与!";
		
		//1.判断该服务是否已经启动
		ShareConfig config  = shareConfigService.getByUserId(user.getId());
		if(config==null || !config.getStartup()){
			reply = "对不起该活动还未启动，感谢您的参与!";
			writeToUser(reply);
			return null;
		} 
		
		//2.判断是否是会员
		WechatMember member =	wechatMemberService.getByWechatMemberId(user, openId);
		if(member !=null){ 
			
			Map<String,Object> params = new HashMap<String, Object>();
			params.put("userId", user.getId());
			params.put("delFlag", 0);
			int rank = daoHelper.queryForTotalRow("com.boxin.ims.wechat.queryShareUsers", params);
			
			if(!config.getRepeats()){	//是否请允许当天重复
				//判断今天是否已上传过
				params.put("day", DateUtils.getTodayString());
				params.put("memberId", member.getId());
				int row =  daoHelper.queryForTotalRow("com.boxin.ims.wechat.queryShareUsers", params);
				if(row>0){
					String str = "";
					if(config.getDisplayRank()){
						str = "您当前的第"+ rank+" 位转发微圈的会员,";
					}
					reply = "亲，对不起，今天您已经上传过了，"+str+"感谢您的参与，试试参与其它的优惠活动吧！";
					writeToUser(reply);
					return  null;
				}
			}
			if(rank==0) rank +=((config.getStartNumber() == null)?0:config.getStartNumber()); 	//设置起始数
			//a. 得名次
			rank = rank +1;		//当前的名次
			//b. 初始化规则
			CircleShare cs = getProcessedShare(rank);
			//c. 规则判断处理
			//d. 回复信息
			ImageMessage imgMsg = new ImageMessage(messageMap);
			final String picUrl = imgMsg.getPicUrl();
			final String topath = Constants.getWechatUserUploadResourceSavePath();
			//final String afx = picUrl.substring(picUrl.lastIndexOf("."),picUrl.length() );
			final String fileName = UUID.randomUUID().toString() + ".png";
			
			new Thread(new Runnable() {
				@Override
				public void run() {
					FileUtils.downloadFile(picUrl, topath, fileName);
				}
			}).start();
			
			CircleShare share = new CircleShare();
			share.setUser(user);
			share.setMember(member);
			share.setUrl(picUrl);
			share.setAwardName((cs==null)?null:cs.getAwardName());			//获得的奖品
			share.setRank(rank);
			share.setWin((cs==null)?false:true);
			share.setEndTime(DateUtils.getDelayDate(config.getValidDays()));
			share.setRemarks((cs==null)?null:cs.getRemarks());
			share.setFileName(fileName);
			
			circleShareService.save(share);
			
			//是否加增加分值
			if(config.getAddScore()!=null && config.getAddScore()){
				ScoreUtils.addScore(member, config.getScore(), "转发有奖增加积分");
			}
			
			
			if(cs!=null){
				reply = "恭喜您获得了微圈分享中奖活动的【"+share.getAwardName()+"】,你是第"+rank+"位分享微圈的人，请务删除此信息,于"+config.getValidDays()+"日内到店里凭此二维码核销使用,过期作废，谢谢！";
				
				
				String title ="转发有奖活动中奖电子凭证";
				
				if(cs.getShareRule()!=null && cs.getShareRule().getScore()!=null && cs.getShareRule().getScore()>0){
					ScoreUtils.addScore(member, cs.getShareRule().getScore(), "转发积分中奖");
					
					//加完积分后直接核销
					if(cs.getShareRule()!=null && CircleShare.YES.equals(cs.getShareRule().getAutoClear())){
						share.setStatus(CircleShare.STATUS_CLEAR);
						share.setUpdateTime(new Date());
						share.setRemarks("成功增了"+cs.getShareRule().getScore()+"个积分并由系统自动核销.");
						circleShareService.save(share);
						
					}
					
					reply = reply.replaceAll("%名次%",rank+"");
					
					reply = "恭喜您获得了微圈分享中奖活动的【"+share.getAwardName()+"】,你是第"+rank+"位分享微圈的人，系统已为您增加了"+cs.getShareRule().getScore()+"个积分并自动核销，谢谢！";
					reply = reply.replaceAll("%中积分%",cs.getShareRule().getScore()+"");
				}
				
				
				if(StringUtils.isNotEmpty(config.getAwardReply())){
					reply = config.getDefaultReply();
					reply = reply.replaceAll("%奖品%", share.getAwardName());
					reply = reply.replaceAll("%名次%",rank+"");
				}
				
				String desc = reply;
				Long qrcodeId = share.getQrCode().getId();
				writeImageToUser(title,desc,qrcodeId);
				return null;
			}else{
				reply = "图片上传成功，谢谢！";
				if(config.getDisplayRank() != null && config.getDisplayRank()){
					reply = "图片上传成功，您是第 "+rank+" 位转发的微会员，感谢您的参与！";
				}
				if(StringUtils.isNotEmpty(config.getDefaultReply())){
					reply = config.getDefaultReply();
				}
			}
			
		}else{
			reply = "亲，您还不是我们的会员请<a href=\"http://www.hdzhx.com/zxims/f/wechat/bind/"+user.getId() +"?wechatId="+openId+"&topage=seckill\">点我申请成为微会员</a>再重新发送分享图片,谢谢！";
		}
		
		writeToUser(reply);		//返回给用户
		
		return null;
	}
	
	
	private CircleShare getProcessedShare(int rank){
		List<ShareRule> shareRules = shareRuleService.findByUserId(user.getId());
		CircleShare cs = new CircleShare();
		
		
		
//		public final static Integer RULE_TYPE_EQUALS = 1;	//与之相等
//		public final static Integer RULE_TYPE_CONTAINS = 2;	//包含 某些数字
//		public final static Integer RULE_TYPE_ALL_SAME = 3; //都相同
//		public final static Integer RULE_TYPE_EVEN = 4;	//偶数
//		public final static Integer RULE_TYPE_ODD  = 5;	//奇数
//		public final static Integer RULE_TYPE_HEADER =6;//开头数
//		public final static Integer RULE_TYPE_TAIL = 7; //属数
//		public final static Integer RULE_TYPE_FORMULA=8;//公式
		
		
		for(ShareRule shareRule:shareRules){
			
			boolean isBreak = false;	//是否中断
			
			String content = shareRule.getRule();
			
			String rk[] = content.split(",");		//规则中定义的 规则数字
			
			cs.setShareRule(shareRule);			//传中传规则
			
			switch (shareRule.getType()) {
				case 1:  //RuleType.RULE_TYPE_EQUALS		等于
					if(rk!=null){
						for(String r:rk){
							if(r.equals(rank+"")){//名次匹配则中奖
								cs.setAwardName(shareRule.getAwardName());
								cs.setRemarks("中奖规则：当前名次等于"+rank);
								isBreak = true;
								break;
							}
						}
					}
					break;
				case 2:	//包含 某些数字
					if(rk!=null){
						for(String r:rk){
							if(r.contains(rank+"")){//名次匹配则中奖
								cs.setAwardName(shareRule.getAwardName());
								cs.setRemarks("中奖规则：当前名次包含"+rank);
								isBreak = true;
								break;
							}
						}
					}
					break;
				case 3:		//都相同  数字中的每一位数字都相同
					if(rk!=null){
						String strRank = rank+"";
						int length = strRank.length();
						String first = strRank.substring(0,1);
						String temp ="";
						for(int i=0;i<length;i++){
							temp +=""+first;
						}
						if(temp.equals(strRank)){
							cs.setAwardName(shareRule.getAwardName());
							cs.setRemarks("中奖规则：当前名次所有位数字都相同->"+rank);
							isBreak = true;
							break;
						}
					}
					break;
				case 4:		//偶数
						if(rank%2 == 0){
							cs.setAwardName(shareRule.getAwardName());
							cs.setRemarks("中奖规则：当前名次是偶数->"+rank);
						}
						isBreak = true;
					break;
				case 5:		//奇数
						if(rank%2 != 0){
							cs.setAwardName(shareRule.getAwardName());
							cs.setRemarks("中奖规则：当前名次是奇数->"+rank);
						}
						isBreak = true;
					break;
				case 6:		//以某数字开头
					if(rk!=null){
						for(String r:rk){
							if( (rank+"").startsWith(r)){//名次匹配则中奖
								cs.setAwardName(shareRule.getAwardName());
								cs.setRemarks("中奖规则：当前名次以"+rank+"开头");
								isBreak = true;
								break;
							}
						}
					}
					break;
				case 7:		//以某数结尾
					if(rk!=null){
						for(String r:rk){
							if( (rank+"").endsWith(r)){//名次匹配则中奖
								cs.setAwardName(shareRule.getAwardName());
								cs.setRemarks("中奖规则：当前名次以"+rank+"结尾");
								isBreak = true;
								break;
							}
						}
					}
					break;
				default:
					break;
			}
			
			if(isBreak) break;	//是否跳出循环
			
		}
		
		return (StringUtils.isEmpty(cs.getAwardName())) ? null:cs;
	}


	@Override
	public boolean isNeedBeMember() {
		return true;
	}
	
	
	

}
